package cc.facesign.servicebase.mqconfig;

import cc.facesign.servicebase.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Configuration
public class RabbitCallBackConfigM {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisCache redisCache;


    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (!b) {
                    log.error("mq: 消息标识:{} 错误原因:{}", correlationData, s);
                    List<Object> list = redisCache.getCacheList("mq:callback");
                    list.add(correlationData);
                    redisCache.setCacheList("mq:callback", list);
                }
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                log.error("mq: 消息体:{} 回复编码:{} 回复内容:{} 交换器:{} 路由键:{}", message, i, s, s1, s2);
                List<Object> list = redisCache.getCacheList("mq:callback");
                list.add(message);
                redisCache.setCacheList("mq:callback", list);
            }
        });
    }
}
